var AV = require('leanengine');
var async = require('async');

var UserCoupon = AV.Object.extend('UserCoupon');
var Coupons = AV.Object.extend('Coupons');
var UserCouponCode = AV.Object.extend('UserCouponCode');

module.exports = {
    //获取用户可用的优惠券列表
    getUserCouponsList:function(openid){
        var timestamp = Date.parse(new Date());
        if(openid){
            var promise = new AV.Promise();
            query = new AV.Query(UserCoupon);
            query.equalTo('uid',openid);
            query.equalTo('used',0);
            query.find().then(function(res){
                var index=0;
                //删除过期
                var couponData=res;
                var couponLen=res.length;
                //console.log(couponLen);
                var i=0;
                for(i;i<couponLen;i++){
                        if(res[i]==null||res[i]==undefined||res[i]==""){
                        }else{
                            if(parseInt(res[i].get('validityEndPeriod'))<timestamp){
                                res.splice(i,1);
                                i--;
                            };
                        }
                }
                promise.resolve(res);
            });
            return promise;
        }else{
            return new AV.Promise.error({code:351});
        }
    },
    //确认订单页面，获取用户可用的优惠券列表
    getUserCouponsListConfirm:function(openid){
        var timestamp = Date.parse(new Date());
        if(openid){
            var promise = new AV.Promise();
            query = new AV.Query(UserCoupon);
            query.equalTo('uid',openid);
            query.equalTo('used',0);
            query.find().then(function(res){
                var index=0;
                //删除过期
                var couponData=res;
                var couponLen=res.length;
                //console.log(couponLen);
                var i=0;
                for(i;i<couponLen;i++){
                    if(res[i]==null||res[i]==undefined||res[i]==""){
                    }else{
                        if(parseInt(res[i].get('validityEndPeriod'))<timestamp || parseInt(res[i].get('validityStartPeriod'))>timestamp){
                            res.splice(i,1);
                            i--;
                        };
                    }
                }
                promise.resolve(res);
            });
            return promise;
        }else{
            return new AV.Promise.error({code:351});
        }
    },
    //通过优惠码领取优惠券
    getCouponCode:function(code,uid,nickname,phone){
        //1.验证优惠码是否被领取
        //2.通过优惠码找到优惠券
        //3.验证优惠券是否过期，数量是否可领
        //4.验证优惠券领取条件
        //5.验证用户是否已领过此批次优惠券
        //6.领取优惠券，插入数据
        //7.更新优惠码状态为已领取
        //8.优惠券数量减一
        var uid=uid;
        var code=code;
        var timestamp = Date.parse(new Date());
        if(code&&uid){
            var promise = new AV.Promise();
            async.waterfall([
                //判断是否存在该优惠码
                function(callback){
                    query = new AV.Query(UserCouponCode);
                    query.equalTo('couponcode',code);
                    query.equalTo('reviced',0);
                    query.first().then(function(res){
                        if(res){
                            callback(null,res.get('cid'));
                        }else{
                            callback({code:352,msg:"优惠码无效"});
                        }
                    })
                },
                //判断是否使用过
                function(cid,callback){
                    query = new AV.Query(UserCoupon);
                    query.equalTo("cid",cid);
                    query.equalTo("uid",uid);
                    query.find().then(function(res){
                        if(res.length){
                            callback({code:353,msg:"用户已经使用过该优惠券"});
                        }else{
                            callback(null,cid);
                        }
                    });
                },
                //判断优惠券是否过期
                function(cid,callback){
                    query = new AV.Query(Coupons);
                    query.equalTo("batchNo",cid);
                    query.first().then(function(res){
                        if(parseInt(res.get('cnt'))>0){
                            if(res.get('receiveEndPeriod')>timestamp){
                                var cnt=parseInt(res.get('cnt'))-1;
                                res.set('cnt',String(cnt));
                                res.save();
                                callback(null,res);
                            }else{
                                callback({code:354,msg:"优惠券已过期"});
                            }
                        }else{
                            callback({code:356,msg:"优惠券已被领完"});
                        }
                    });
                },
                //领取优惠券
                function(res,callback){
                    query = new AV.Query(UserCouponCode);
                    query.equalTo('couponcode',code);
                    query.first().then(function (res) {
                        res.set("reviced",1);
                        res.save();
                    });
                    var takeCoupon = new UserCoupon();
                    var newCoupon={'uid':uid,'cid':res.get("batchNo"),'uphone':phone,'uname':nickname,'validityEndPeriod':res.get("validityEndPeriod"),'used':0,'status':1,coupon:res.attributes};
                    takeCoupon.save(newCoupon).then(function(res){
                        callback(null,{code:0,msg:"领取成功",res:res});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            if(!code){
                return new AV.Promise.error({code:355});
            }else{
                return new AV.Promise.error({code:351});
            }
        }

    },
    //直接领取优惠券
    getCoupon:function(cid,uid,nickname,phone){
        var timestamp = Date.parse(new Date());
        if(cid&&uid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    query = new AV.Query(UserCoupon);
                    query.equalTo("cid",cid);
                    query.equalTo("uid",uid);
                    query.find().then(function(res){
                        if(res.length){
                            callback({code:353,msg:"用户已经使用过该优惠券"});
                        }else{
                            callback(null,cid);
                        }
                    });
                },
                //判断优惠券是否过期
                function(cid,callback){
                    query = new AV.Query(Coupons);
                    query.equalTo("batchNo",cid);
                    query.greaterThan("cnt",0);
                    query.first().then(function(res){
                        if(res){
                            if(res.get('receiveEndPeriod')>timestamp){
                                res.increment('cnt',-1);
                                res.save();
                                callback(null,res)
                            }else{
                                callback({code:354,msg:"优惠券已过期"});
                            }
                        }else{
                            callback({code:354,msg:"优惠券已过期"});
                        }
                    });
                },
                //领取优惠券
                function(res,callback){
                    var takeCoupon = new UserCoupon();
                    var newCoupon={'uid':uid,'cid':res.get("batchNo"),'uphone':phone,'uname':nickname,'used':0,'status':1,coupon:res.attributes};
                    takeCoupon.save(newCoupon).then(function(res){
                        callback(null,{code:0,msg:"领取成功",res:res});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            if(!cid){
                return new AV.Promise.error({code:357});
            }else{
                return new AV.Promise.error({code:351});
            }
        }
    },
    //通过扫描二维码领取优惠券
    receiveCouponScan:function(){
        //1.获取优惠券批号，验证当前用户是否已领过此批号优惠券
        //2.验证优惠券是否过期，数量是否可领
        //3.验证优惠券领取条件
        //4.领取优惠券，插入数据
        //5.领取成功，优惠券数量减一
    },
    //拆分优惠券接口
    //TODO

    /*
     * 更新优惠卷状态
     * Add By James 2015-09-13
     * @param objectId 订单ID  type 更新状态 1:变更为已使用　　0：变更为未使用
     */
    updateUserCoupon:function(objectId,type){
        if(!objectId){
            return new AV.Promise.error({code:350});        //优惠券编号不能为空
        }

        //if(type == ''){
        //    return new AV.Promise.error({code:351});        //更新状态不能为空
        //}

        var promise = new AV.Promise();
        var query = new AV.Query(UserCoupon);

        async.waterfall([
            function(callback){
                //根据objectId获取该对象
                query.get(objectId).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                if(res.get('used') == type){
                    //该优惠券已经使用过了　
                    callback(null,{code:0});
                }else{
                    //获取到对象，则更新状态为1
                    res.set('used',parseInt(type));
                    res.save().then(function(o){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    }
};